const CryptoJS = require("crypto-js");

module.exports = () => {
    return async function verified(ctx, next) {
        let path = ctx.path.toLowerCase();
        if (!path.startsWith("/api")||path.includes("types")||path.includes("announces") || path.includes("books") || 
        path === "/api/v1/user/login"|| 
        path=="/api/v1/library/config") {
            await next();
            return;
        }

        if (!ctx.header.authorization) {
            ctx.throw(401, 'unauthorization!');
        }

        let token = CryptoJS.AES.decrypt(ctx.header.authorization, ctx.app.config.keys, { iv: 0, mode: CryptoJS.mode.CBC }).toString(CryptoJS.enc.Utf8);
        let userInfo = token.split("||");
        if (userInfo.length != 5 || Number(userInfo[4]) < new Date().getTime()) {
            ctx.throw(401, 'unauthorization!');
        }

        ctx.state.user = {
            id: Number(userInfo[0]),
            accountName: userInfo[1],
            nickName: userInfo[2],
            role: userInfo[3],
        }
        await next();
    };
};